package com.hemaapp.yjnh.activity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseApplication;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.bean.ZouzouDate;
import com.hemaapp.yjnh.view.calendar.CalendarCellDecorator;
import com.hemaapp.yjnh.view.calendar.CalendarPickerView;
import com.hemaapp.yjnh.view.calendar.CalendarPickerView.SelectionMode;
import com.hemaapp.yjnh.view.calendar.SampleDecorator;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;

/**
 * 选择时间 type = 1:多选 type = 2:范围多选,type = 其他:单选
 * */
@SuppressLint("ClickableViewAccessibility") 
public class CalendarActivity extends BaseActivity {

	private ImageButton left;
	private Button right;
	private TextView title;


	private CalendarPickerView calendar;

	private SampleDecorator decorator;
	private SelectionMode selectionMode;
	private String refusedates="";
	private int monthCount = 0;//已经获取的不可用日期月份数量
	private ArrayList<ZouzouDate> dates = new ArrayList<ZouzouDate>();
	private Calendar unuseCa;//获取不可用日期时使用

	private User user;
	private String id;
	private int style = 0;//显示类型：0只是查看日期，1可以选择日期。

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_calendar);
		super.onCreate(savedInstanceState);
		user = BaseApplication.getInstance().getUser();
		init();
		unuseCa = Calendar.getInstance();
		getUnuseDateList();
	}
	
	private void getUnuseDateList() {
		String token = "";
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
		if (user != null) {
			token = user.getToken();
		}
		getNetWorker().zouzouDateList(token, id, format.format(unuseCa.getTime()), "0");
		monthCount++;
		unuseCa.add(Calendar.MONTH, 1);
	}

	private void init() {
		final Calendar nextYear = Calendar.getInstance();
		nextYear.add(Calendar.MONTH, 3);//向后显示6个月的日期(包含当月)
		final Calendar lastYear = Calendar.getInstance();//获取当前的日期
		lastYear.add(Calendar.MONTH, 0);//向上前显示0个月

		calendar = (CalendarPickerView) findViewById(R.id.calendar_view);
		List<CalendarCellDecorator> decorators = new ArrayList<CalendarCellDecorator>();

		decorator = new SampleDecorator();
		decorators.add(decorator);
		calendar.setDecorators(decorators);//设置完装饰性属性之后，刷新adapter显示出来
		calendar.setRefusedates(refusedates);

        //是否是仅查看模式，start uu
		selectionMode = SelectionMode.SINGLE;//设置为单选模式
		if (style == 1) {
		    calendar.init(lastYear.getTime(), nextYear.getTime(), true)
	        .inMode(selectionMode) //设置选择模式
	        .withSelectedDate(new Date());//设置默认被选择的日期
        }else {
            calendar.init(lastYear.getTime(), nextYear.getTime(), false)
            .inMode(selectionMode) //设置选择模式
            .withSelectedDate(new Date());//设置默认被选择的日期
        }
        //是否是仅查看模式，end uu

	}

	@Override
	protected void callBeforeDataBack(HemaNetTask netTask) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case TRAVEL_DATE_LIST:
			showProgressDialog("请稍候");
			break;
		default:
			break;
		}
	}

	@Override
	protected void callAfterDataBack(HemaNetTask netTask) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case TRAVEL_DATE_LIST:
			cancelProgressDialog();
			break;
		default:
			break;
		}
	}

	@Override
	protected void callBackForServerSuccess(HemaNetTask netTask,
			HemaBaseResult baseResult) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case TRAVEL_DATE_LIST:
			@SuppressWarnings("unchecked")
			HemaPageArrayResult<ZouzouDate> zResult = (HemaPageArrayResult<ZouzouDate>) baseResult;
			String month = netTask.getParams().get("month");
			dates.addAll(zResult.getObjects());
			if (monthCount < 6) {
				getUnuseDateList();
			}else {
				if (dates.size() > 0) {
					refusedates = handlerUnuseDate(dates);
					calendar.setRefusedates(refusedates);
				}
			}
			break;
		default:
			break;
		}
	}
	
	/**处理服务器返回的走走不可用日期
	 * @param dates
	 * @return
	 */
	private String handlerUnuseDate(ArrayList<ZouzouDate> dates) {
		String result = "";
		String from_date = "";
		String to_date = "";
		try {
			for (ZouzouDate date : dates) {
				from_date = date.getfrom_date();
				to_date = date.getto_date();
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

				Date fDate = format.parse(from_date);
				Calendar fCalendar = Calendar.getInstance();
				fCalendar.setTime(fDate);
				Date tDate = format.parse(to_date);
				Calendar tCalendar = Calendar.getInstance();
				tCalendar.setTime(tDate);
				int early = fCalendar.compareTo(tCalendar);

				while (early != 1) {
					//early==1,开始时间大于结束时间
					//early==0,开始时间等于结束时间
					//early==-1,开始时间小于结束时间
					result = result + format.format(fCalendar.getTime()) + ",";
					fCalendar.add(Calendar.DAY_OF_MONTH, 1);
					early = fCalendar.compareTo(tCalendar);
				}
			}
			result.substring(0, result.length()-1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	@Override
	protected void callBackForServerFailed(HemaNetTask netTask,
			HemaBaseResult baseResult) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case TRAVEL_DATE_LIST:
			showTextDialog(baseResult.getMsg());
			title.postDelayed(new Runnable() {
				
				@Override
				public void run() {
					finish();
				}
			}, 1000);
			break;
		default:
			break;
		}
	}

	@Override
	protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case TRAVEL_DATE_LIST:
			showTextDialog("获取数据失败");
			title.postDelayed(new Runnable() {
				
				@Override
				public void run() {
					finish();
				}
			}, 1000);
			break;
		default:
			break;
		}
	}

	@Override
	protected void findView() {
		left = (ImageButton) findViewById(R.id.title_left_btn);
		right = (Button) findViewById(R.id.title_right_btn);
		title = (TextView) findViewById(R.id.title_text);

	}

	@Override
	protected void getExras() {
		style = mIntent.getIntExtra("style", 0);
		id = mIntent.getStringExtra("id");
	}

	@Override
	protected void setListener() {
		right.setText("确定");
		if (style == 0) {
			right.setVisibility(View.GONE);
			title.setText("查看可用日期");
		}else {
			right.setVisibility(View.VISIBLE);
			title.setText("选择日期");
		}
		left.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		right.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
					Date date=calendar.getSelectedDate();//获取选中的日期
					mIntent.putExtra("date", format.format(date));
					setResult(RESULT_OK, mIntent);
					finish();
			}
		});
	}
}
